#!/bin/bash

# Docling Web App - 启动脚本
# 自动激活虚拟环境并启动应用

set -e

# 获取脚本目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VENV_DIR="$SCRIPT_DIR/venv"

echo "🚀 启动 Docling Web 应用..."
echo "=================================================="

# 检查虚拟环境是否存在
if [ ! -d "$VENV_DIR" ]; then
    echo "❌ 错误: 虚拟环境不存在"
    echo "请先运行: ./setup_venv.sh"
    exit 1
fi

# 检查虚拟环境中的Python
if [ ! -f "$VENV_DIR/bin/python" ]; then
    echo "❌ 错误: 虚拟环境损坏"
    echo "请重新运行: ./setup_venv.sh"
    exit 1
fi

# 激活虚拟环境
echo "⚡ 激活虚拟环境..."
source "$VENV_DIR/bin/activate"

# 检查app.py是否存在
if [ ! -f "$SCRIPT_DIR/app.py" ]; then
    echo "❌ 错误: 未找到 app.py 文件"
    exit 1
fi

# 加载环境变量
if [ -f "$SCRIPT_DIR/.env" ]; then
    echo "🔧 加载环境变量..."
    export $(cat "$SCRIPT_DIR/.env" | grep -v '^#' | xargs)
fi

# 设置默认环境变量
export HF_ENDPOINT=${HF_ENDPOINT:-https://hf-mirror.com}
export HF_HOME=${HF_HOME:-$SCRIPT_DIR/models_cache}
export OMP_NUM_THREADS=${OMP_NUM_THREADS:-4}

# 显示配置信息
echo "📋 应用配置:"
echo "   项目目录: $SCRIPT_DIR"
echo "   虚拟环境: $VENV_DIR"
echo "   Python: $(python --version)"
echo "   HF镜像: $HF_ENDPOINT"
echo "   模型缓存: $HF_HOME"
echo ""

# 检查核心依赖
echo "🔍 检查核心依赖..."
python -c "import flask; print(f'✅ Flask {flask.__version__}')" || {
    echo "❌ Flask未安装，请运行: ./setup_venv.sh"
    exit 1
}

python -c "import docling; print('✅ Docling已安装')" || {
    echo "❌ Docling未安装，请运行: ./setup_venv.sh"
    exit 1
}

# 创建必要目录
mkdir -p "$SCRIPT_DIR/uploads"
mkdir -p "$SCRIPT_DIR/models_cache"
mkdir -p "$SCRIPT_DIR/static/uploads"

echo "🎯 启动Web应用..."
echo "=================================================="
echo "📱 应用将在以下地址运行:"
echo "   本地访问: http://localhost:5000"
echo "   局域网访问: http://0.0.0.0:5000"
echo ""
echo "⏹️  按 Ctrl+C 停止应用"
echo "=================================================="
echo ""

# 启动应用
cd "$SCRIPT_DIR"
python app.py
